import { roundTrial, format } from "./calculator";
import { Wrapper, CardsDeck } from '../game-blackjack/index'
import { useEffect, useState } from "react";

const initial = () => {
  const all:any[] = []
  for (let row = 0;row<4;row++) {
    for (let col = 0;col<9;col++) {
      all.push({ row, col, points: col + 1 })
    }
  }

  const size = all.length
  const cardsIdx = []
  while(cardsIdx.length < 4) {
    const r = Math.floor(Math.random() * size)
    if ( cardsIdx.indexOf(r) < 0) cardsIdx.push(r)
  }

  return cardsIdx.map((x) => all[x])
}

export default function Demo() {
  const [cards, setCards] = useState<any[]>([])
  const [solutions, setSolutions] = useState<any[]>([])
  const [rslt, setRslt] = useState<number|undefined|null>(null)
  const [visible, setVisible] = useState<boolean>(false)

  const onStart = () => {
    const cards = initial()
    setVisible(false)
    setCards(cards)
  }

  useEffect(() => {
    if (!cards.length) return

    const solutions: any[] = []
    const rslt = roundTrial(cards.map((x) => x.points || 0), 0, [], solutions)
    setRslt(rslt)
    setSolutions(solutions)
  }, [cards])

  return (
    <Wrapper>
      <h1 style={{textAlign: 'center', fontSize: '4rem'}}>
        Math 24
      </h1>

      <div style={{display: 'flex', gap: '1rem'}}>
        <button onClick={onStart} >Let's go</button>
        <button onClick={() => setVisible((x) => !x)} >
          {visible ? 'Hide' : 'Show'} answer
        </button>
      </div>

      <div className='players-area'>

        <div className='players-block'>
          <CardsDeck cards={cards} gap={90} />
        </div>
      </div>


      { (visible) && (!!rslt) &&
        <div style={{textAlign: 'left'}}>
          { solutions.map((solution: any, idx:number) => (
            <p>
              <span>{idx}#&nbsp;&nbsp;</span>
              { solution.map((x:any, index:number) => (
              <>
                { (index > 0) && <span>, &nbsp;</span> }
                <span>{format(x.a, x.b, x.op)}</span>
              </>
              ))}
            </p>
          ))}
        </div>
      }
      { (visible) && (!rslt) &&
        <div>No way</div>
      }

    </Wrapper>
  );
}
